package com.cf.end.cowboy;

import com.cf.common.util.encrypt.MD5coding;
import com.cf.game.Player;
import com.cf.game.cowboy.CowBoyGame;
import com.cf.game.cowboy.config.CowboyMessageRegister;
import com.cf.game.service.pojo.H5Game;
import com.cf.game.service.pojo.UserInfo;
import com.cf.game.service.service.UserInfoService;
import com.cf.game.service.service.h5game.H5GameService;
import com.cf.game.service.util.RedisContants;
import com.cf.game.service.util.StringUtils;
import com.cf.serialize.Message;
import com.cf.serialize.MessageConvertService;
import com.cf.serialize.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import javax.annotation.PostConstruct;
import javax.websocket.Session;
import java.io.IOException;

/**
 * websocket-BizssEndPoint
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/2/28 10:58
 */


@Component("cowboy")
public class CowBoyEndPoint {

    private Logger logger = LoggerFactory.getLogger(CowBoyEndPoint.class);

    @Autowired
    private H5GameService gameService;

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private UserInfoService userInfoService;

    private CowBoyGame cowBoyGame;

    @Autowired
    private CowboyMessageRegister cowboyMessageRegister;

    private MessageConvertService messageService = new MessageConvertService();

    @PostConstruct
    public void init() {
        cowBoyGame = new CowBoyGame();
        H5Game h5Game = gameService.getGameByGameCode(cowBoyGame.getGameCode());
        cowBoyGame.init(h5Game);
        cowboyMessageRegister.register(messageService);
    }

    private void addTestUserToken(String id) {
        String uuid = MD5coding.getInstance().encrypt(id);
        System.out.println(uuid);
        jedisCluster.set(RedisContants.LOGIN_KEY + id, uuid);
        jedisCluster.set(RedisContants.LOGIN_KEY + uuid, id);
    }

    /**
     * 连接建立成功调用的方法
     */
    public void onOpen(Session session) {
        logger.info("onOpen");
        session.setMaxIdleTimeout(120 * 1000l);
    }

    /**
     * 连接关闭调用的方法
     */
    public void onClose(Session session) {
        logger.info("close");
        cowBoyGame.leaveGame(session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    public void onMessage(String message, Session session) throws IOException {
        logger.info("onMessage");
        Message serialize = messageService.serialize(message);

        if (serialize instanceof Request) {
            Request request = (Request) serialize;
            Integer userId = getUserIdFromRedis(request.getUserToken());
            if (userId == null) {
                logger.info("消息未经授权，非法访问，拒绝！【{}】", message);
                return;
            }
            UserInfo userInfo = userInfoService.selectUserNameAndUserImg(userId);
            Player player = cowBoyGame.enterGame(userInfo, session);
            cowBoyGame.handleMessage(player, request);

        }

    }

    public void onError(Session session, Throwable error) {
        logger.info("onError");
        cowBoyGame.leaveGame(session);
        error.printStackTrace();
    }

    public Integer getUserIdFromRedis(String token) {
        String s = jedisCluster.get(RedisContants.LOGIN_KEY + token);
        if (StringUtils.hasLength(s))
            return Integer.valueOf(s);
        else
            return null;
    }

}
